package com.cyzy.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cyzy.common.constant.MessageConstant;
import com.cyzy.common.exception.LoginFailedException;
import com.cyzy.common.properties.WeChatProperties;

import com.cyzy.common.utils.HttpClientUtil;
import com.cyzy.pojo.dto.MyDTO;
import com.cyzy.pojo.dto.UserLoginDTO;
import com.cyzy.pojo.entity.StudentAuth;
import com.cyzy.pojo.entity.User;
import com.cyzy.server.dao.HuntCardDao;
import com.cyzy.server.dao.RecruitCardDao;
import com.cyzy.server.dao.StarDao;
import com.cyzy.server.dao.UserDao;
import com.cyzy.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RecruitCardDao recruitCardDao;
    @Autowired
    private StarDao starDao;
    @Autowired
    private HuntCardDao huntCardDao;
    /**
     * 微信登陆
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    @Transactional
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，接收当前微信用户的openid
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否为新用户
        User user = userDao.getByOpenid(openid);

        //如果是新用户，自动完成注册
        if (user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userDao.insert(user);
        }
        //返回这个用户对象


        return user;
    }

    @Override
    @Transactional
    public MyDTO getMyInfo(Integer userId) {

        MyDTO my = new MyDTO();

        User user = userDao.getById(userId);

        if (user==null){
            return null;
        }

        BeanUtils.copyProperties(user,my);

        return my;
    }

    @Override
    @Transactional
    public void setProfile(Integer id, Map map) {
        userDao.setProfile(id, (String) map.get("name"), (String) map.get("phoneNumber"));
    }

    @Override
    public void setAvatar(String path, Integer id) {
        userDao.setAvatar(path, id);
    }

    @Override
    public String studentAuth(StudentAuth studentAuth) {
        String url = "http://jwxt.gdufe.edu.cn/jsxsd/xk/LoginToXkLdap";
        String username = studentAuth.getUserName();
        String password = studentAuth.getPassword();
        String randomCode = studentAuth.getRandomCode();
        String cookieValue = studentAuth.getCookie();
        String errorMessage = null;

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 添加 Cookie 到请求头
            httpPost.setHeader("Cookie", "JSESSIONID=" + cookieValue);

            // 构建请求参数
            String requestBody = "USERNAME=" + urlEncode(username) + "&PASSWORD=" + urlEncode(password) + "&RANDOMCODE=" + urlEncode(randomCode);
            StringEntity entity = new StringEntity(requestBody);
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                String responseBody = EntityUtils.toString(responseEntity, "UTF-8");
                System.out.println("响应状态码: " + response.getStatusLine().getStatusCode());
                //System.out.println("响应体: " + responseBody);
                 errorMessage = null;

                try {
                    // 使用Jsoup解析HTML内容
                    Document doc = Jsoup.parse(responseBody);

                    // 找到带有红色字体的标签
                    Elements elements = doc.select("font[color=red]");

                    // 提取其中的文本内容
                    if (!elements.isEmpty()) {
                        Element errorElement = elements.first();
                        errorMessage = errorElement.text();
                        System.out.println(errorMessage);
                    }
                    //System.out.println(elements);
                    return errorMessage;


                } catch (Exception e) {
                    e.printStackTrace();
                    // 处理异常情况
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return errorMessage;
    }
    private static String urlEncode(String value) throws UnsupportedEncodingException {
        return URLEncoder.encode(value, "UTF-8");
    }
}
